#coding:utf-8
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.syndication.feeds import FeedDoesNotExist
from django.contrib.syndication.feeds import Feed
from vleApp.models import News, Group

class NewsFeed(Feed):
    title_template = 'feeds/title.html'
    description_template = 'feeds/description.html'

    def get_object(self, courseData):
        """courseData is a list of params retrieved from the url
        if url is /feeds/news/courseCode/groupCode/
        then courseData will be:
        [courseCode,groupCode] with the slug news (on urlConf)
        """
        if len(courseData) != 2:
            #It must be 2 in order to retrieve a right feed
            raise ObjectDoesNotExist
        print len(courseData)
        #No need to round the next statement with try/catch, django throws an ObjectDoesNotExist->404, on failure
        return Group.objects.filter(course__code=courseData[0]).get(code=courseData[1])

    def title(self,obj):
        '''Defines the title based on the object, here the object is a Group
           it was retrieved by get_object method previously'''
        print "en Title()"
        return "Noticias del %s" %(unicode(obj).encode('utf-8'))

    def link(self,obj):
        print "en link()"
        return obj.get_absolute_url()

    def description(self,obj):
        print "en description()"
        return "10 noticias recientes del %s"%(unicode(obj).encode('utf-8'))

    def items(self,obj):
        print "en items()"
        return News.objects.filter(groups__id=obj.id).order_by('-date')[:10]

    def item_link(self,item):
        return 'http://localhost:8000%s'%(item.get_absolute_url())

class Prueba(Feed):
    title ="Feed de Noticias de Prueba"
    link = "/home/"
    description = "Esto es una gran prueba"

    def items(self):
        return News.objects.order_by('-date')[:10]


    



